﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using DBService;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Runtime.Serialization.Json;
using System.Xml.Linq;

public partial class FbLogin : System.Web.UI.Page
{
    ModelAdapter ma = new ModelAdapter();


    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            string app_id = "296010147167377";
            string app_secret = "390d195e3cb50ab79392c33e53b546ca";
            string app_url = "http://revio.ge/fblogin.aspx";

            string code = Request.QueryString["code"];

            if (!String.IsNullOrEmpty(code))    // TODO and Session states matches
            {
                string url = String.Format(@"https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}",
                    app_id, app_url, app_secret, code);

                WebClient webClient = new WebClient();

                var tokenVars = webClient.DownloadString(url);

                var responseVars = HttpUtility.ParseQueryString(tokenVars);
                string access_token = responseVars["access_token"];
                Session["access_token"] = access_token;
                var expires = responseVars["expires"];
                string data = webClient.DownloadString(String.Format("https://graph.facebook.com/me?access_token={0}", access_token));

                var jobject = JObject.Parse(data);
                var fbUserID = (string)jobject["id"];
                var fbFirstName = (string)jobject["first_name"];
                var fbLastName = (string)jobject["last_name"];
                var fbSex = (string)jobject["gender"];
                var fbMail = (string)jobject["email"];
                var fbBirthDay = (string)jobject["birthday"];

                ///// prevent login banned user
                try
                {
                    var bannedUsersXml = XElement.Load(AppDomain.CurrentDomain.BaseDirectory + "/App_Data/BannedUsers.xml");
                    var node = bannedUsersXml
                    .Elements("user").Where(u => u.Value == fbUserID)
                    .FirstOrDefault();
                    if (node != null)
                    {
                        Response.Redirect("~/BannedUser.aspx", true);
                    }
                }
                catch
                {

                }

                DBService.User usr;
                DateTime bday;
                try
                {
                    bday = Convert.ToDateTime(fbBirthDay);
                }
                catch
                {
                    bday = DateTime.Now.AddYears(-25);
                }
                int success = ma.ImportUserFromFB(fbUserID, fbFirstName, fbLastName, fbMail, fbSex == "male", bday, 1, out usr);
                if (success > 0 && usr != null)
                {
                    LoginUser(usr);
                    AddCookiesUserInfo(usr);
                    //WriteOnFace(success, access_token);
                    //Response.Redirect("userprofile.aspx?id=" + usr.UserID);
                    Response.Redirect("aboutus.aspx");
                }
            }
        }
        catch { }
    }

    public static void WriteOnFace(int action, string accessToken)
    {
        try
        {

            string urlll = "";
            WebClient wc = new WebClient();
            switch (action)
            {
                case 0:
                    //urlll = "https://graph.facebook.com/feed?access_token=" + accessToken + "&message=" + "მე დავრეგისტრირდი Revio.ge - ზე! სცადე შენც" + "&method=post";
                    //wc.DownloadString(urlll);
                    break;
                case 1:
                    urlll = "https://graph.facebook.com/feed?access_token=" + accessToken + "&message=" + "http://www.revio.ge : შეაფასე და მოიგე Kindle Fire და iPod Touch 5th Gen!" + "&method=post";
                    wc.DownloadString(urlll);
                    break;
                case 2:
                    //urlll = "https://graph.facebook.com/feed?access_token=" + accessToken + "&message=" + "მე დავრეგისტრირდი Revio.ge - ზე! სცადე შენც" + "&method=post";
                    //wc.DownloadString(urlll);
                    break;
                default:
                    break;
            }
        }
        catch (Exception)
        {

        }
    }

    protected void LoginUser(User usr)
    {
        if (String.IsNullOrEmpty(usr.Avatar))
        {
            Session["Avatar"] = "images/no-avatar.jpeg";
        }
        else
        {
            Session["Avatar"] = "upload/" + usr.Avatar;
        }
        Session["UserID"] = usr.UserID;
        Session["UserType"] = usr.UserType;
        Session["Email"] = usr.Email;
        Session["FirstName"] = usr.FirstName;
        Session["LastName"] = usr.LastName;
        Session["Gender"] = usr.Gender;
        Session["Likes"] = usr.Likes;
        Session["Dislikes"] = usr.Dislikes;
        Session["DateOfBirth"] = usr.DateOfBirth;
        Session["FaceID"] = usr.FaceID;
    }

    public void AddCookiesUserInfo(User user)
    {
        HttpCookie cookie = new HttpCookie("UserInfo");
        if (String.IsNullOrEmpty(user.Avatar))
        {
            cookie["Avatar"] = "images/no-avatar.jpeg";
        }
        else
        {
            //UserAvatar.Src = "upload/" + usr.Avatar;
            cookie["Avatar"] = "upload/" + user.Avatar;
        }
        cookie["UserID"] = user.UserID.ToString();
        cookie["UserType"] = user.UserType == null ? "1" : user.UserType.ToString();
        cookie["Email"] = user.Email;
        cookie["FirstName"] = user.FirstName;
        cookie["LastName"] = user.LastName;
        cookie["Gender"] = user.Gender.HasValue ? user.Gender.ToString() : "";
        cookie["Likes"] = user.Likes == null ? "0" : user.Dislikes.ToString();
        cookie["Dislikes"] = user.Dislikes == null ? "0" : user.Dislikes.ToString();
        cookie["DateOfBirth"] = user.DateOfBirth.HasValue ? user.DateOfBirth.ToString() : "";
        cookie["FaceID"] = user.FaceID.ToString();
        cookie.Expires = DateTime.Now.AddDays(1);
        Response.Cookies.Add(cookie);
    }

    public static T Deserialise<T>(string json)
    {
        T obj = Activator.CreateInstance<T>();
        using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
            obj = (T)serializer.ReadObject(ms); // <== Your missing line
            return obj;
        }
    }

}
